package com.whfc.fvs.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.result.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description: 乐橙工具类
 * @author: qzexing
 * @version: 1.0
 * @date: 2020/3/16 17:21
 */
public class ImouUtil {

    /**
     * 初始化获取Token的参数
     *
     * @return paramsMap
     */
    public static Map<String, Object> paramsInit(String appKey, String appSecret) {

        long time = System.currentTimeMillis() / 1000;
        String nonce = UUID.randomUUID().toString();
        String id = UUID.randomUUID().toString();

        StringBuilder paramString = new StringBuilder();
        paramString.append("time:").append(time).append(",");
        paramString.append("nonce:").append(nonce).append(",");
        paramString.append("appSecret:").append(appSecret);

        String sign = "";
        // 计算MD5得值
        try {
            System.out.println("传入参数：" + paramString.toString().trim());
            sign = DigestUtils.md5Hex(paramString.toString().trim().getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> systemMap = new HashMap<>();
        systemMap.put("ver", "1.0");
        systemMap.put("sign", sign);
        systemMap.put("appId", appKey);
        systemMap.put("nonce", nonce);
        systemMap.put("time", time);

        Map<String, Object> map = new HashMap<>();
        map.put("system", systemMap);
        map.put("id", id);
        return map;
    }

    /**
     * 处理返回结果
     *
     * @param response response
     * @return Result
     */
    public static Result parseResult(String response) {
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject != null) {
            String resultStr = jsonObject.getString("result");
            if (StringUtils.isNotEmpty(resultStr)) {
                return JSON.parseObject(resultStr, Result.class);
            }
        }
        return null;
    }

}
